package com.example.mykotlin.base.flex

import com.example.mykotlin.base.util.tryOnly
import com.github.yitter.idgen.YitIdHelper
import com.mybatisflex.core.keygen.IKeyGenerator
import java.lang.reflect.Field
import org.springframework.util.ReflectionUtils

class YitterKeyGenerator : IKeyGenerator {
    override fun generate(entity: Any, keyColumn: String): Any {
        val nextId = YitIdHelper.nextId()
        tryOnly {
            val clazz = entity::class.java
            val field: Field = ReflectionUtils.findField(clazz, keyColumn)!!
            field.setAccessible(true)
            val columnValue = field.get(entity)
            if (columnValue != null) {
                return columnValue
            }
            val type = field.type
            return when (type) {
                Long::class.java -> nextId
                Int::class.java -> nextId
                else -> nextId.toString()
            }
        }
        return nextId.toString()
    }
}